<?php

namespace api\modules\v1\models;

use Yii;
use api\common\models\User as U;
use yii\helpers\ArrayHelper;
class User extends U
{

    public function rules()
    {
       return ArrayHelper::merge(parent::rules(), [
            ['collect_category', 'required','message'=>'栏目收藏ID不能为空', 'on' => ['collect']],
            ['collect_category', 'validateCategory', 'on' => ['collect']],
            ['collect_category', 'safe', 'on' => ['collect']],
        ]);
    }

    /*
     *  用户收藏栏目
     */
    public function sc(){
        if ($this->validate()) {
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }


    /*
     * 验证分类格式是否存在
     * @param $attribute
     * @param $params
     * @return bool
     */
    public function validateCategory($attribute, $params)
    {
        $collect_category = explode('|',$this->collect_category);
        foreach($collect_category as $value){
            $value = explode(',',$value);
            foreach($value as $v){
                if(!is_numeric($v)){
                    $this->addError($attribute, '参数错误 必须为integer');
                }
            }
        }

        //针对收藏栏目 必须显示在第一个
        foreach($collect_category as $key=>$value){
            if($value == 555){
                $recommend_cate = $value;
                unset($collect_category[$key]);
            }
        }
        array_unshift($collect_category,$recommend_cate);
        $this->collect_category = implode('|',$collect_category);

        return true;
    }
}
